package com.zhuoyue.biz.core.command.cmd.common.fbe;

import com.zhuoyue.biz.core.api.domain.DeviceAndGatewayDO;
import com.zhuoyue.biz.core.api.dto.req.ControlReq;
import com.zhuoyue.biz.core.command.model.HumanInfraredCmd;
import com.zhuoyue.common.constant.ControlType;
import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import com.zhuoyue.common.utils.CmdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 人体红外传感器
 *
 * @author wjming
 */
@Component
public class HumanInfrared {
    private static final String SET_MODE = "0201${gatewayMac}${deviceMac}03F70101${time}";
    private static RedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        HumanInfrared.redisTemplate = redisTemplate;
    }

    /**
     * @param deviceAndGatewayDo
     * @param controlReq
     * @return
     */
    public static String setControl(DeviceAndGatewayDO deviceAndGatewayDo, ControlReq controlReq) {
        String gatewayMac = deviceAndGatewayDo.getGatewayMac();
        String zigbeeMac = deviceAndGatewayDo.getZigbeeMac();
        final int bigTime = 255;
        switch (controlReq.getControlType()) {
            case ControlType.GENERAL_SET:
                Object time = controlReq.getActions().get("time");
                Integer timeInt = (Integer) time;
                if (timeInt > bigTime) {
                    throw new ZyServerException(ErrorType.INVALID_PARAMS);
                }
                String timeHex;
                if (time != null) {
                    timeHex = CmdUtils.intToHexTwo((Integer) time);
                } else {
                    timeHex = CmdUtils.intToHexTwo(10);
                }
                redisTemplate.opsForValue().set("com.zyzn.infrared.time." + gatewayMac, deviceAndGatewayDo.getId() + "_" + time, 10, TimeUnit.SECONDS);
                return new HumanInfraredCmd(gatewayMac, zigbeeMac, timeHex).getCmd(SET_MODE);
            default:
                break;
        }
        return "";
    }
}
